package cn.iocoder.yudao.module.wms.service.doc;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.DocNoTypeEnum;
import cn.iocoder.yudao.module.wms.dal.redis.RedisKeyConstants;
import cn.iocoder.yudao.module.wms.dal.redis.doc.DocRedisDAO;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.wms.controller.admin.doc.vo.*;
import cn.iocoder.yudao.module.wms.dal.dataobject.doc.DocDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wms.dal.mysql.doc.DocMapper;

import javax.annotation.Resource;

import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wms.enums.ErrorCodeConstants.*;

/**
 * 仓储单据 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DocServiceImpl implements DocService {

    @Resource
    private DocMapper docMapper;
    @Resource
    private DocRedisDAO docRedisDAO;

    @Override
    public Long createDoc(DocSaveReqVO createReqVO) {
        // 校验编码
        validateCodeExists(null, createReqVO.getCode());
        // 插入
        DocDO doc = BeanUtils.toBean(createReqVO, DocDO.class);
        docMapper.insert(doc);
        // 返回
        return doc.getId();
    }

    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.WMS_DOC, key = "#updateReqVO.id")
    public void updateDoc(DocSaveReqVO updateReqVO) {
        // 校验存在
        validateDocExists(updateReqVO.getId());
        // 更新
        DocDO updateObj = BeanUtils.toBean(updateReqVO, DocDO.class);
        // 防更新部分字段
        updateObj.setCode(null);
        updateObj.setDocType(null);
        updateObj.setTransactionType(null);

        docMapper.updateById(updateObj);
    }

    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.WMS_DOC, key = "#id")
    public void deleteDoc(Long id) {
        // 校验存在
        validateDocExists(id);
        //TODO 如果单据已被使用，不允许删除
        // 删除
        docMapper.deleteById(id);
    }

    private DocDO validateDocExists(Long id) {
        DocDO doc = docMapper.selectById(id);
        if (ObjectUtil.isEmpty(doc)) {
            throw exception(DOC_NOT_EXISTS);
        }
        return doc;
    }

    private void validateCodeExists(Long id, String code) {
        DocDO doc = docMapper.selectByCode(code);
        if (ObjectUtil.isEmpty(doc)) {
            return;
        }
        if (ObjectUtil.isNotEmpty(id)) {
            throw exception(DOC_CODE_EXISTS);
        }
        if (!doc.getId().equals(id)) {
            throw exception(DOC_CODE_EXISTS);
        }
    }

    @Override
    @Cacheable(cacheNames = RedisKeyConstants.WMS_DOC, key = "#id", unless = "#result == null")
    public DocDO getDoc(Long id) {
        return validateDocExists(id);
    }

    @Override
    public PageResult<DocDO> getDocPage(DocPageReqVO pageReqVO) {
        return docMapper.selectPage(pageReqVO);
    }

    @Override
    public String getDocNo(Long id) {
        DocDO doc = validateDocExists(id);
        // 处理编号日期段
        String date = DocNoTypeEnum.getNo(doc.getDocNoType());
        if (StrUtil.isBlank(date)) {
            throw exception(DOC_NO_TYPE_NOT_EXISTS);
        }
        String serial = docRedisDAO.increment(doc.getCode(), 1);
        if (StrUtil.isBlank(serial)) {
            throw exception(DOC_NO_FAILED);
        }
        if (serial.length() < doc.getDocNoLength()) {
            serial = String.format("%0" + doc.getDocNoLength() + "d", Integer.valueOf(serial));
        }
        return doc.getDocNoPrefix() + date + serial;
    }

    @Override
    public List<DocDO> getDocList(Collection<Long> ids) {
        return docMapper.selectList(ids);
    }

}